package org.ccay.log.connection.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Properties;

import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.ccay.core.request.IUserPrincipal;
import org.ccay.core.request.impl.RequestContext;
import org.ccay.core.request.impl.RequestContextConstants;
import org.ccay.core.request.impl.RequestContextManager;
import org.ccay.core.util.StringUtil;
import org.ccay.log.connection.IDatabaseConnectionLog;


/**
 * was服务器的连接记录对象
 * @author chaowangbang
 *
 */
public class WasDatabaseConnectionLog implements IDatabaseConnectionLog{
	
	private static ILogger logger = CcayLoggerFactory.getLogger(WasDatabaseConnectionLog.class);

	/**
	 * 记录Connection中日志
	 * (non-Javadoc)
	 * @see org.ccay.log.connection.IDatabaseConnectionLog#log(java.sql.Connection)
	 */
	public void log(Connection connection) {
		try {
				logger.debug("[In WasDatabaseConnectionLog class the Connection is:]"+connection);
				 //获取请求上下文
				String userInfo = this.getUserOPInfo();
				if(StringUtil.isNullOrEmpty(userInfo)){
					return;
				}
				@SuppressWarnings("rawtypes")
				Class cls = connection.getClass();
				Method method  = cls.getMethod("setClientInformation", Properties.class);
			
				Properties props = new Properties();
				props.setProperty("CLIENT_ID", userInfo);
				logger.debug("User Information:"+props.getProperty("CLIENT_ID"));
				//存储用户帐号、角色、用户操作的资源地址
				 method.invoke(connection, props);
			} catch (SecurityException e) {
				logger.error(e);
			} catch (NoSuchMethodException e) {
				logger.error(e);
			}  catch (IllegalAccessException e) {
				logger.error(e);
			} catch (InvocationTargetException e) {
				logger.error(e);
			}catch (RuntimeException e) {
				logger.error(e);
			}  
		  
	}

	/**
	 * 获取用户信息
	 * @return
	 */
	private String getUserOPInfo(){
		
		//定义属性对象，存储用户帐号、角色、用户操作的资源地址
		RequestContext context = (RequestContext) RequestContextManager.getCurrent(true);
		if(context == null){
			return null;
		}
			//获取当前登录用户
		 IUserPrincipal user = context.getUser();
		String userInfo = null;
		if (user != null) {
			StringBuilder userOPInfo = new StringBuilder();
			//获取用户帐号,获取当前登录用户角色
			userOPInfo.append(user.getUserName());
			userOPInfo.append( ":");
			//获取当前用户操作的资源地址
			String url = (String) context.getItem(RequestContextConstants.KEY_URI);
			logger.debug("User Information url:"+url);
			userOPInfo.append(url);						 
			//存储64位长度
			userInfo = userOPInfo.toString();
			if (userInfo.length() > 64) {
				userInfo = userInfo.substring(0, 64);
			} 
			
		}
		return userInfo;
  
	}
}
